// goods.js

var api = require('../../api.js');
var utils = require('../../utils.js');
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var p = 1;
var is_loading_comment = false;
var is_more_comment = true;
var share_count = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bottom: app.BOTTOM_DISTANCE,//iponeX底部需要抬高的距离
    imgServer: api.default.img_server,
    id: null,
    goods: {},
    price: 0,
    stock: 0,
    show_attr_picker: false,
    subImages: [],
    form: {
      number: 1,
    },
    tab_detail: "active",
    tab_comment: "",
    comment_list: [],
    comment_count: {
      score_all: 0,
      score_3: 0,
      score_2: 0,
      score_1: 0,
    },
    autoplay: false,
    hide: "hide",
    show: false,
    x: wx.getSystemInfoSync().windowWidth,
    y: wx.getSystemInfoSync().windowHeight - 20,
    spArr: [],//用户选择的规格参数
    sp1: "",
    sp2: "",
    sp3: "",
    skuCode: "",
    skuId: "",
    show_param_picker: false,//商品参数弹窗展示与否
    show_service_picker: false,//服务说明的弹窗展示与否
    brand: {},//当前商品的品牌信息
    curDepotId: null,//当前仓库id
    showBackTop: false,//是否显示向上的按钮
    isSalesman:false,
    moneyIcon:api.MONEYICON,
    moneyIconOther:api.MONEYICONOTHER,
    selectedPic:null,//选中的sku的图片
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let token = wx.getStorageSync('token');
    
    if(token){
      let share_code = wx.getStorageSync("user_sharecode");
      if(!share_code){
        app.checkUserIditity(this.checkUserIdentityCall);
      }else{
        this.checkUserIdentityCall();
      }
    }
  },
  checkUserIdentityCall(){
    let share_code = wx.getStorageSync("user_sharecode");
    if(share_code){//是经销商，可以展示分享二维码
      this.setData({
        isSalesman:true,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("promotion页的options")
    console.log(options);
    if(options.scene){
      let queryarr=decodeURIComponent(options.scene).split("&")
      let urlobj={};
      queryarr.map(item=>{
        let left = item.split('=')[0];
        let right = item.split('=')[1];
        urlobj[left] = right
      })
      let id = urlobj.oId;
      let share_code = urlobj.dCode;
      options.id=id;
      options.share_code =share_code;
    }
    let page = this;
    if(options.productType){
      page.setData({
        productType: options.productType
      })
    }
    if (options.id){
      page.getGoods(options.id);
      page.setData({
        id: options.id
      })
    }
    
    //被推广人打开页面的时候，如果有share_code，要进行绑定  
    //但是被推广人没有登录的情况肯定很多，所以把这个码先放到缓存中，登录成功以后，再进行绑定
    
    if (options.share_code) {
      let token = wx.getStorageSync("token");
      if (!token) {
        wx.setStorage({
          key: "share_code",//别人分享的别人的二维码，上一级的分享码
          data: options.share_code
        })
      } else {
        app.bindSalesInfo(options.share_code);
      }
    }
    // share_count = 0;
    // p = 1;
    // is_loading_comment = false;
    // is_more_comment = true;

    // var parent_id = 0;
    // var user_id = options.user_id;
    // console.log("options=>" + JSON.stringify(options));
    // var scene = decodeURIComponent(options.scene);
    // if (user_id != undefined) {
    //     parent_id = user_id;
    // } else if (scene != undefined) {
    //     console.log("scene string=>" + scene);
    //     var scene_obj = utils.scene_decode(scene);
    //     console.log("scene obj=>" + JSON.stringify(scene_obj));
    //     if (scene_obj.uid && scene_obj.gid) {
    //         parent_id = scene_obj.uid;
    //         options.id = scene_obj.gid;
    //     } else {
    //         parent_id = scene;
    //     }
    // }
    // app.loginBindParent({parent_id: parent_id});
    // var page = this;
    // page.setData({
    //     id: options.id,
    // });

    // page.getCommentList();
  },
  onClickHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  getGoods: function (goodId) {
    let page = this;
    app.request({
      url: api.default.goodsDetail + goodId,
      success: function (res) {
        if (res.code == 200) {
          let data = res.data;
          var detail = data.detailMobileHtml;
          WxParse.wxParse("detail", "html", detail, page);
          let tempdepotProductDTOS = data.depotProductDTOS;

          if (tempdepotProductDTOS.length > 0) {
            for (const item of tempdepotProductDTOS) {
              item.checked = false;
            }
            tempdepotProductDTOS[0].checked = true;
          }

          let attr_group_list = data.productAttributeDetailValue.productSpecsAttributeList;
          attr_group_list.map((val, index) => {
            let tempArr = val.attributeValue.split(",");
            val.attributeValue = [];
            tempArr.map((val1, idx) => {
              val.attributeValue.push({
                value: val1,
                checked: false,
                disabled: true,//默认都不可以选择
              })
            })
          });

          let tempsubImages = data.pic + (data.albumPics ? ',' + data.albumPics : '');//不知道为啥分了俩字段
          //关联商品标题和答疑
          let relatedProductsInfo = {};
          let questionAndAnswer = {};
          for (const item of data.productDetailConfigDTOS) {
            if (item.key == "answerAnduarantee") {
              if (item.content != "") {
                questionAndAnswer = item.content;
                let content = questionAndAnswer;
                WxParse.wxParse("content", "html", content, page);
              } else {
                questionAndAnswer.content = "<p>抱歉，该类目下暂无说明</p>"
              }
            } else {
              if (item.content != "" && item.relationProductList && item.relationProductList.length > 0) {
                relatedProductsInfo = item;
              }
            }
          }
          let promotionSet = null;
          let showPrice = 0;
          let max = 0;
          let isFlashProduct = false;//是否为秒杀商品
          let countDownTime = 0;//倒计时
          if (!data.flashPromotionProduct || Object.keys(data.flashPromotionProduct).length == 0) {
            // showPrice = data.exchangePrice;
            showPrice = data.price;
            max = data.stock;
          } else {
            promotionSet = data.flashPromotionProduct;
            // showPrice = promotionSet.exchangeFlashPromotionPrice;
            showPrice = promotionSet.flashPromotionPrice;
            max = promotionSet.flashPromotionLimit;
            isFlashProduct = true;
            let nowTime = new Date(data.systemTime);
            let year = nowTime.getFullYear();
            let month = nowTime.getMonth();
            let date = nowTime.getDate();

            let endhour = promotionSet.endTime.split(":")[0];
            let endminute = promotionSet.endTime.split(":")[1];
            let endsecond = promotionSet.endTime.split(":")[2];
            let fendTime = new Date(year, month, date, endhour, endminute,endsecond).getTime();

            //let fend = year+'-'+month+'-'+date+' '+promotionSet.endTime;
            //console.log(fend);
            //let fendTime = new Date(fend).getTime();

            countDownTime = parseInt(fendTime - nowTime.getTime());
          }
          page.setData({
            goods: data,
            brand: data.brandDTO,
            price: showPrice,
            stock: data.stock,
            maxInputNum: max,
            promotionSet: promotionSet,
            attr_group_list: attr_group_list,
            depotProductDTOS: tempdepotProductDTOS,
            curDepotId: tempdepotProductDTOS[0].depotId,
            subImages: tempsubImages.split(","),
            param_group_list: data.productAttributeDetailValue.productParamAttributeList,
            //service_group_list: serviceDesc,
            relatedProductsInfo: relatedProductsInfo,//关联商品
            questionAndAnswer: questionAndAnswer,//答疑
            isFlashProduct: isFlashProduct,//是否是秒杀商品
            countDownTime: countDownTime,//倒计时
          });
          let event = {
            currentTarget: {
              dataset: {
                id: tempdepotProductDTOS[0].depotId
              }
            }
          };
          page.depotClick(event);
        }else{
          wx.showModal({
            title: '提示',
            content: res.message,
            cancelText:"返回",
            confirmText:"回首页",
            success (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              } else if (res.cancel) {
                wx.navigateBack();
              }
            }
          })
        }
      }
    })
  },
  getCommentList: function (more) {
    var page = this;
    if (more && page.data.tab_comment != "active")
      return;
    if (is_loading_comment)
      return;
    if (!is_more_comment)
      return;
    is_loading_comment = true;
    app.request({
      url: api.default.comment_list,
      data: {
        goodsId: page.data.id,
        pageNum: p,
      },
      success: function (res) {
        if (res.code != 200)
          return;
        is_loading_comment = false;
        p++;
        page.setData({
          comment_count: res.data.count,
          comment_list: more ? page.data.comment_list.concat(res.data.list) : res.data.list,
        });
        if (res.data.list.length == 0)
          is_more_comment = false;
      }
    });
  },
  onGoodsImageClick: function (e) {
    var page = this;
    var urls = [];
    var index = e.currentTarget.dataset.index;
    //console.log(page.data.goods.pic_list);
    for (var i in page.data.goods.pic_list) {
      urls.push(page.data.goods.pic_list[i].pic_url);
    }
    let picList = page.data.subImages;
    wx.previewImage({
      urls: picList, // 需要预览的图片http链接列表
      current: index,
    });
  },

  numberSub: function () {
    var page = this;
    var num = page.data.form.number;
    if (num <= 1)
      return true;
    num--;
    page.setData({
      form: {
        number: num,
      }
    });
  },

  numberAdd: function () {
    var page = this;
    var num = page.data.form.number;
    let max = page.data.maxInputNum;
    let curStock = page.data.stock;
    if (curStock <= 0) {
      wx.showToast({
        title: "库存不足请重选",
        image: "/images/icon-warning.png",
        duration: 2000
      });
      return;
    }
    console.log(max);
    if (max && max > 0 && num >= max) {
      wx.showToast({
        title: '每人限购' + max + '件',
        icon: "none"
      });
      return
    }
    num++;
    page.setData({
      form: {
        number: num,
      }
    });
  },

  numberBlur: function (e) {
    var page = this;
    var num = e.detail.value;
    num = parseInt(num);
    if (isNaN(num))
      num = 1;
    if (num <= 0)
      num = 1;
    page.setData({
      form: {
        number: num,
      }
    });
  },

  addCart: function () {
    this.submit('ADD_CART');
  },

  buyNow: function () {
    this.submit('BUY_NOW');
  },

  submit: function (type) {
    var token = wx.getStorageSync("token");
    var page = this;
    if (!token) {
      wx.navigateTo({
        url: '/pages/allow/allow',
        events: {
          acceptDataFromOpenedPage(data) {
            if (data.hasLogin) {
              wx.navigateBack();
              page.getGoods(data.goodsId);
            }
          }
        },
        success: function (res) {
          res.eventChannel.emit('acceptDataFromOpenerPage', { goodsId: page.data.goods.id })
        }
      })
      return;
    }
    //要添加attr长度的判断
    if (!page.data.show_attr_picker) {
      page.setData({
        show_attr_picker: true,
      });
      return true;
    }
    if (!page.data.skuId || !page.data.skuCode) {
      wx.showToast({
        title: "请选择商品属性！",
        image: "/images/icon-warning.png",
        duration: 2000
      });
      return true;
    }
  
    if (type == 'ADD_CART') {//加入购物车

      wx.showLoading({
        title: "正在提交",
        mask: true,
      });
      let tempdata={
        //userid:access_token,
        //id: attr_group.id,
        productDepotId: page.data.curDepotId,
        productCategoryId: page.data.goods.productCategoryId,
        brandId: page.data.goods.brandId,
        productBrand: page.data.goods.brandName,
        sp1: page.data.sp1,
        sp2: page.data.sp2,
        sp3: page.data.sp3,
        quantity: page.data.form.number,
        productSn: page.data.goods.productSn,
        productSkuId: page.data.skuId,
        productSkuCode: page.data.skuCode,
        productId: page.data.goods.id,
        //price: page.data.price || page.data.goods.price,//这里如果没有规格,取页面上显示的价格
        productName: page.data.goods.name,
        productPic: page.data.goods.pic
      };
      app.request({
        url: api.cart.add_cart,
        method: "POST",
        data: tempdata,
        success: function (res) {
         

          page.setData({
            show_attr_picker: false,
          });
        },
        complete(res){
          if (res.data.code == 200) {
            wx.showToast({
              title: res.message||'成功加入购物车~',
              icon: 'none',
              duration: 1500
            });

          }
          else {
            //console.log("报错了@#￥%……&&&&&&*********")
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            });
          }
        }
      });
    }
    if (type == 'BUY_NOW') {//立即购买
      page.setData({
        show_attr_picker: false,
      });
      wx.showLoading({
        title: "正在提交",
        mask: true,
      });
      let tempdata2={
        // userid:access_token,
        // id: attr_group.id,
        productDepotId: page.data.curDepotId,
        productCategoryId: page.data.goods.productCategoryId,
        brandId: page.data.goods.brandId,
        productBrand: page.data.goods.brandName,
        sp1: page.data.sp1,
        sp2: page.data.sp2,
        sp3: page.data.sp3,
        quantity: page.data.form.number,
        productSn: page.data.goods.productSn,
        productSkuId: page.data.skuId,
        productSkuCode: page.data.skuCode,
        productId: page.data.goods.id,
        price: page.data.price || page.data.goods.price,//这里如果没有规格,取页面上显示的价格
        productName: page.data.goods.name,
        productPic: page.data.goods.pic
      };
      app.request({
        url: api.cart.add_cart,
        method: "POST",
        data: tempdata2,
        success: function (res) {
          wx.showToast({
            title: res.message,
            duration: 1500
          });
          wx.hideLoading();
          page.setData({
            show_attr_picker: false,
          });
          console.log('cartId=' + res.data);
          if (res.data) {
            let transferdata ={
              //cartIds: res.data,
              cart_id_list:res.data,
              count: page.data.form.number,
              depotId: page.data.curDepotId
            }
            if(page.data.productType){
              transferdata.productType = page.data.productType
            }
            wx.redirectTo({
              url: "/pages/order-submit/order-submit?goods_info=" + JSON.stringify(transferdata),
            });
          } else {
            wx.showToast({
              title: res.message || '返回参数有误，请重试',
              icon: "none"
            })
          }
        }
      });
    }
  },

  hideAttrPicker: function () {
    var page = this;
    page.setData({
      show_attr_picker: false,
    });
  },
  showAttrPicker: function () {
    var page = this;
    page.setData({
      show_attr_picker: true,
    });
  },

  showParamPicker: function () {
    var page = this;
    page.setData({
      show_param_picker: true,
    });
  },
  hideParamPicker: function () {
    var page = this;
    page.setData({
      show_param_picker: false
    });
  },
  showServicePicker: function () {
    var page = this;
    page.setData({
      show_service_picker: true,
    });
  },
  hideServicePicker: function () {
    var page = this;
    page.setData({
      show_service_picker: false,
    });
  },
  depotClick(event) {
    let page = this;
    let depotid = event.currentTarget.dataset.id;
    let depotList = page.data.depotProductDTOS;
    for (let depot of depotList) {
      if (depot.depotId == depotid) {
        depot.checked = true
      } else {
        depot.checked = false
      }
    }
    app.request({
      url: api.default.getDepotDetail + depotid + '/' + page.data.goods.id,
      method: 'get',
      success: function (res) {
        if (res.code == 200) {
          let data = res.data && res.data.skuStockList;
          let attr_group = page.data.attr_group_list;
          let sp1List = [], sp2List = [], sp3List = [];
          for (let attr of attr_group) {//初始化，全部置为false
            for (let arrtDetail of attr.attributeValue) {
              arrtDetail.checked = false;
              arrtDetail.disabled = true;
            }
          }
          for (const item of data) {
            item.sp1 ? sp1List.push(item.sp1) : '';
            item.sp2 ? sp2List.push(item.sp2) : '';
            item.sp3 ? sp3List.push(item.sp3) : "";
          };

          sp1List = Array.from(new Set(sp1List));
          sp2List = Array.from(new Set(sp2List));
          sp3List = Array.from(new Set(sp3List));
          // console.log(sp1List);
          // console.log(sp2List);
          // console.log(sp3List);
          if (sp1List.length > 0) {
            let attrList = attr_group[0] && attr_group[0].attributeValue;
            for (var sp1item of sp1List) {
              for (const item2 of attrList) {
                if (sp1item == item2.value) {
                  item2.disabled = false;
                  continue
                }
                // else{
                //     item2.disabled = true;
                // }
              }
            }
          }
          if (sp2List.length > 0) {
            let attrList = attr_group[1] && attr_group[1].attributeValue;
            for (const item of sp2List) {
              for (const item2 of attrList) {
                if (item == item2.value) {
                  item2.disabled = false;
                  continue
                }
                //  else{
                //     item2.disabled = true;
                // }
              }
            }
          }
          if (sp3List.length > 0) {
            let attrList = attr_group[2] && attr_group[2].attributeValue;
            for (const item of sp3List) {
              for (const item2 of attrList) {
                if (item == item2.value) {
                  item2.disabled = false;
                  continue
                }
                // else{
                //     item2.disabled = true;
                // }
              }
            }
          }
          page.setData({
            curDepotId: depotid,
            depotProductDTOS: depotList,
            attr_group_list: attr_group,
            // price:page.data.goods.flashPromotionProduct.flashPromotionPrice || page.data.goods.price,//没有选中sku的时候，显示当前商品的价格和库存
            // stock:page.data.goods.stock,
            skuCode: null,
            skuId: null,
          });
          console.log(page.data.attr_group_list);
        //  if(attr_group.length==1){
            let param ={
              value:data[0].sp1,
              title:attr_group[0].attributeName
            };
            page.attrClick(null,param)
         // }
        } else {
          wx.showModal({
            title: "提示",
            content: res.message,
          })
        }

      }
    })
  },
  attrClick: function (e,param) {
    var page = this;

    // var attr_group_id = e.target.dataset.groupId; // skuCode
    // var attr_id = e.target.dataset.id; // goodsid
    var attr_val = e?e.target.dataset.val:param.value; // value
    var attr_title = e?e.target.dataset.title:param.title; // title
    var attr_group_list = page.data.attr_group_list;
    var attr_group;
    //var spArr=[];
    for (var i in attr_group_list) {
      if (attr_group_list[i].attributeName == attr_title) {
        attr_group_list[i].attributeValue.map((val, index) => {
          if (val.value === attr_val && !val.checked) {
            attr_group_list[i].attributeValue[index].checked = true;
          } else {
            attr_group_list[i].attributeValue[index].checked = false;

          }
        })
        // attr_group_list[i].checked = true;
        // attr_group=attr_group_list[i];
      }
    }
    let tempSpArr = [];
    for (let item of attr_group_list) {
      for (let item2 of item.attributeValue) {
        item2.checked == true ? tempSpArr.push(item2.value) : ""
      }
    }
    console.log(tempSpArr);
    console.log(attr_group_list);
    //console.log(page.data.spArr);
    page.data.spArr = tempSpArr;
    if (page.data.spArr.length == attr_group_list.length) {
      //let sp1, sp2, sp3;
      page.data.spArr.map((val, index) => {
        if (index == 0) {
          page.data.sp1 = val;
        } else if (index == 1) {
          page.data.sp2 = val;
        } else {
          page.data.sp3 = val;
        }
      });
      console.log(page.data.sp1, page.data.sp2, page.data.sp3);
      page.setData({
        attr_group_list: attr_group_list,
        sp1: page.data.sp1,
        sp2: page.data.sp2,
        sp3: page.data.sp3,
        // attr_group : attr_group
      });
      app.request({
        url: api.default.getAttrDetail,
        method: 'post',
        data: {
          productId: page.data.goods.id,
          depotId: page.data.curDepotId,
          sp1: page.data.sp1,
          sp2: page.data.sp2,
          sp3: page.data.sp3,
        },
        success: function (res) {
          // console.log(res);
          if (res.code == 200) {
            if (res.data && res.data.stock > 0) {
              let data = res.data;
              let price = data.flashPromotionProduct ? data.flashPromotionProduct.flashPromotionPrice : data.price;
              let max = data.flashPromotionProduct ? data.flashPromotionProduct.flashPromotionLimit : data.stock
              page.setData({
                price: price,
                stock: data.stock,
                maxInputNum: max,
                skuCode: data.skuCode,
                skuId: data.id,
                selectedPic:data.pic?data.pic:null
                // attr_group : attr_group,
              });
            } else {
              page.setData({
                //price : page.data.goods.flashPromotionProduct.flashPromotionPrice|| page.data.goods.price,
                stock: 0,
                skuCode: null,
                skuId: null,
                // attr_group : attr_group,
                selectedPic:null
              });
              wx.showToast({
                title: "库存不足请重选",
                image: "/images/icon-warning.png",
                duration: 2000
              });
            }
          }else{
            wx.showToast({
              title: res.message ,
              image: "/images/icon-warning.png",
              duration: 2000
            });
          }
        }
      })
    } else {
      page.setData({
        attr_group_list: attr_group_list,
        //   price:page.data.goods.price,//没有选中sku的时候，显示当前商品的价格和库存//sku信息置空
        //   stock:page.data.goods.stock,
        skuCode: null,
        skuId: null,
        selectedPic:null
        // attr_group : attr_group
      });
    }
  },
  favoriteAdd: function () {
    var page = this;
    var access_token = wx.getStorageSync("token");
    if(!access_token){
      wx.navigateTo({
        url: '/pages/allow/allow',
        events: {
          acceptDataFromOpenedPage(data) {
            if (data.hasLogin) {
              wx.navigateBack();
              page.getGoods(data.goodsId);
            }
          }
        },
        success: function (res) {
          res.eventChannel.emit('acceptDataFromOpenerPage', { goodsId: page.data.goods.id })
        }
      })
      return;
    }
    var user_info = wx.getStorageSync("user_info");

    app.request({
      url: api.user.favorite_add,
      method: "post",
      data: {
        // type:1,
        // memberId:21,
        productName: page.data.goods.name,
        productPic: page.data.goods.pic,
        productSubTitle: page.data.goods.subTitle,
        productPrice: page.data.goods.price,
        productId: page.data.goods.id,
      },
      success: function (res) {
        if (res.code == 200) {
          var goods = page.data.goods;
          goods.isFavorite = 1;
          let newGoods = {};
          newGoods['goods.isFavorite'] = 1;//收藏
          // page.setData({
          //   goods: goods,
          // });
          page.setData(newGoods);
        }
      }
    });
  },
  favoriteRemove: function () {
    var page = this;
    var access_token = wx.getStorageSync("access_token");
    app.request({
      url: api.user.favorite_remove + '/' + page.data.goods.id,
      //method: "post",
      //data: page.data.goods.id,
      // {
      //   //   type:1,
      //   //   userid:21,
      //   // memberId: 21,
      //   //goodsid: page.data.goods.id,
      //   productId: page.data.goods.id,
      // },
      success: function (res) {
        if (res.code == 200) {
          var goods = page.data.goods;
          goods.isFavorite = 0;
          let newGoods = {};
          newGoods['goods.isFavorite'] = 2;//未收藏
          // page.setData({
          //   goods: goods,
          // });
          page.setData(newGoods);
        }
      }
    });
  },

  tabSwitch: function (e) {
    var page = this;
    var tab = e.currentTarget.dataset.tab;
    if (tab == "detail") {
      page.setData({
        tab_detail: "active",
        tab_comment: "",
      });
    } else {
      page.setData({
        tab_detail: "",
        tab_comment: "active",
      });
    }
  },
  commentPicView: function (e) {
    var page = this;
    var index = e.currentTarget.dataset.index;
    var pic_index = e.currentTarget.dataset.picIndex;
    wx.previewImage({
      current: page.data.comment_list[index].pic_list[pic_index],
      urls: page.data.comment_list[index].pic_list,
    });
  },
  onPageScroll: function (e) {
    // console.log(e) 自己设置 滚动距离,200
    if (e.scrollTop > 1000) {
      this.setData({
        showBackTop: true
      });
    } else {
      this.setData({
        showBackTop: false
      });
    }
  },
  backTop() {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  onCountDownChange(e) {
    this.setData({
      timeData: e.detail
    });
    let { hours, minutes, seconds } = e.detail
    if (hours == 0 && minutes == 0 && seconds == 0) {
      this.setData({
        'isFlashProduct': false,//当前时间段的秒杀结束 
      })
      //this.getGoods(this.data.id);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var page = this;
    //page.getCommentList(true);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var page = this;
    var user_info = wx.getStorageSync("user_info");
    let share_code = wx.getStorageSync("user_sharecode") || '';//经销商（自己）的分享码
    let shareImgUrl = page.data.subImages[0];
    var res = {
      path: "/pages/goods/goods?id=" + this.data.id + "&share_code=" + share_code,
      title: page.data.goods.name,
      imageUrl: shareImgUrl,
    };
    return res;
  },
  play: function (e) {
    var url = e.target.dataset.url;//获取视频链接
    this.setData({
      url: url,
      hide: '',
      show: true,
    });
    var videoContext = wx.createVideoContext('video');
    videoContext.play();
  },

  close: function (e) {
    if (e.target.id == 'video') {
      return true;
    }
    this.setData({
      hide: "hide",
      show: false
    });
    var videoContext = wx.createVideoContext('video');
    videoContext.pause();
  },
  hide: function (e) {
    if (e.detail.current == 0) {
      this.setData({
        img_hide: ""
      });
    } else {
      this.setData({
        img_hide: "hide"
      });
    }
  },

  showShareModal: function () {
    var page = this;
    page.setData({
      share_modal_active: "active",
      no_scroll: true,
    });
  },

  shareModalClose: function () {
    var page = this;
    page.setData({
      share_modal_active: "",
      no_scroll: false,
    });
  },

  getGoodsQrcode: function () {
    var page = this;
    page.setData({
      goods_qrcode_active: "active",
      share_modal_active: "",
    });
    // if (page.data.goods_qrcode)
    //     return true;
    app.request({
      url: api.share.getShareQrcode,
      method:'post',
      data: {
        path:'pages/goods/goods',
        appid:api.APPID,
        orderId: page.data.id,
      },
      success: function (res) {
        if (res.code == 200) {
          page.setData({
            goods_qrcode: res.data,
          });
        }
      },
    });
  },

  goodsQrcodeClose: function () {
    var page = this;
    page.setData({
      goods_qrcode_active: "",
      no_scroll: false,
    });
  },

  saveGoodsQrcode: function () {
    var page = this;
    if (!wx.saveImageToPhotosAlbum) {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }

    wx.showLoading({
      title: "正在保存图片",
      mask: false,
    });

    wx.downloadFile({
      url: page.data.goods_qrcode,
      success: function (e) {
        wx.showLoading({
          title: "正在保存图片",
          mask: false,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function () {
            wx.showModal({
              title: '提示',
              content: '商品二维码保存成功',
              showCancel: false,
            });
          },
          fail: function (e) {
            // wx.showModal({
            //   title: '图片保存失败',
            //   content: e.errMsg,
            //   showCancel: false,
            // });
          },
          complete: function (e) {
            console.log(e);
            wx.hideLoading();
          }
        });
      },
      fail: function (e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ";" + page.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function (e) {
        console.log(e);
        wx.hideLoading();
      }
    });

  },

  goodsQrcodeClick: function (e) {
    var src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
  closeCouponBox: function (e) {
    this.setData({
      get_coupon_list: ""
    });
  },
  wxParseTagATap(e){
    let url = e.currentTarget.dataset.src;
    wx.navigateTo({
      url: '/'+url,
    })
  },

});